var setting = {
	view: {
		addHoverDom: false,
		removeHoverDom: false,
		selectedMulti: false
	},
	check: {
		enable: false
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	edit: {
		enable: false
	},
	callback: {
		onClick: onClick
	}
};
var settings1 =  {
		view : {
			dblClickExpand : false
		},
		data : {
			simpleData : {
				enable : true
			}
		}
	};


var setting2 = {
		view : {
			dblClickExpand : false
		},
		data : {
			simpleData : {
				enable : true
			}
		}
	};

var selectedNodeTemp = null;   
var treeSelectInputId = "parentDept_insert_id";
$(document).ready(function(){
	
	deptTreeListLoad("");
	
	$('#deptLeaderRealName_insert').select2({
		placeholder: "选择员工名称",
		language: "zh-CN", 
		data:[],
		closeOnSelect:true,
		dropdownAutoWidth:true,
		allowClear: true,
		disabled:false,
		multiple:false,
		width:"100%"
	});
	
	$('#deleteDeptInfoModal').on('show.bs.modal', function (event) {
		// select 选中部门
		var treeObj = $.fn.zTree.getZTreeObj("deptTreeData");
		var nodes = treeObj.getSelectedNodes();
		if(nodes.length !== 1){
			toastr.warn("您当前没有选中要删除的部门信息","提示信息");
			return false;
		}
		$("#delDeptInfoModal_content").find(".modal-body").text("确认删除【"+($("#deptName").val())+"】部门信息吗？");
		
	});
	
	
	//id选择器选中modal框
	$('#insertDeptInfoModal').on('show.bs.modal', function (event) {
		
		var button = $(event.relatedTarget);
		let titleMsg = "";
		let type = button.attr("execute-type");
		if(type === 'insert'){
			titleMsg = "增加部门信息";
			$('#deptLeaderRealName_insert').empty();
			$('#deptLeaderRealName_insert').select2({
				 data: [],
				 width:"100%"
			});
			resetSaveForm();
			if(selectedNodeTemp !== null){
				if(typeof (selectedNodeTemp.id) !== "undefined" && selectedNodeTemp.id  !== null && (selectedNodeTemp.id).toString().trim() !== ""){
					$("#"+treeSelectInputId).val(selectedNodeTemp.name);
					$("#"+treeSelectInputId).attr("data-tree-id",selectedNodeTemp.id);
					deptSelectCompoment(selectedNodeTemp.id);
				}
			}
			
		}else if(type === 'update'){
			var treeObj = $.fn.zTree.getZTreeObj("deptTreeData");
			var nodes = treeObj.getSelectedNodes();
			if(nodes.length !== 1){
				toastr.warn("您当前没有选中要修改的部门信息！","提示信息");
				return false;
			}
			titleMsg = "更新部门信息";
			selectedNodeSyncForm();
			$.ajax({
				url:"/sysDept/getUserLeaderTree",
				type:"POST",
				contentType: "application/json;charset=UTF-8",
				timeout:10000,
				data:"{'deptId':'"+$("#deptId_insert").val()+"'}",
				async:true,
				cache:false,
				dataType:"json",
				success:function(data){
					if(data.code == 200){
						$('#deptLeaderRealName_insert').empty();
						$('#deptLeaderRealName_insert').select2({
							placeholder: "选择员工名称",
							language: "zh-CN", 
							 data: data.selectData,
							 closeOnSelect:true,
							dropdownAutoWidth:true,
							allowClear: true,
							disabled:false,
							multiple:false,
							width:"100%"
						});
						if(selectedNodeTemp != null){
							if(typeof (selectedNodeTemp.leaderUserId) !== "undefined" && selectedNodeTemp.leaderUserId != null && (selectedNodeTemp.leaderUserId).toString().trim() !== ""){
								$('#deptLeaderRealName_insert').val(selectedNodeTemp.leaderUserId).trigger('change');
							}else{
								$('#deptLeaderRealName_insert').val(null).trigger('change');
							}
							
						}
					}
				},error:function(e){
					$('#deptLeaderRealName_insert').empty();
					$('#deptLeaderRealName_insert').select2({
						placeholder: "选择员工名称",
						language: "zh-CN", 
						data:[],
						closeOnSelect:true,
						dropdownAutoWidth:true,
						allowClear: true,
						disabled:false,
						multiple:false,
						width:"100%"
					});
					selectedNodeSyncForm();
				}
			});
		}
		$('#insertDeptInfoModalLabel').text(titleMsg);
		
	})
	
});

function deptTreeListLoad(saveAfterDeptId){
	
	$.ajax({
		url:"/sysDept/getTree",
		type:"GET",
		contentType: "application/json;charset=UTF-8",
		timeout:10000,
		async:true,
		cache:false,
		dataType:"json",
		beforeSend:function(){
			$("#baseDeptId").val("");
			$("#deptName").val("");
			$("#parentDept").val("");
			$("#deptLeaderRealName").val("");
			$("#deptLeaderTelPhone").val("");
			$("#deptLeaderPhone").val("");
			$.fn.zTree.destroy("deptTreeData");
			$("#treeErrorMsg").html("数据正在加载中......").show();
		},
		success:function(data){
			if(data.code == 200){
				$("#treeErrorMsg").html("").hide();
				var treeObj = $.fn.zTree.init($('#deptTreeData'), setting, data.treeData);
				if(typeof(treeObj) !== "undefined" && treeObj != null){
					var nodes = null;
					if(saveAfterDeptId !== ""){
						nodes = treeObj.getNodesByParam("id", saveAfterDeptId, null);
					}else{
						nodes = treeObj.getNodes();
					}
					if(typeof(nodes) !== "undefined" && nodes != null && nodes.length > 0){
						onClick(null,"deptTreeData",nodes[0],null);
						treeObj.selectNode(nodes[0]);
					}
				}
				$("#parentDept_insert").treeSelect({
			        data: data.treeData,
			        inputId:treeSelectInputId
			    });
			}else{
				$("#treeErrorMsg").html("加载部门列表失败，原因:"+data.msg+"。[<a class='text-primary' click='deptTreeListLoad()'>重新加载</a>]").show();
			}
		},error:function(e){
			$("#treeErrorMsg").text("加载部门列表失败，请联系系统管理员查询相关问题！[<a class='text-primary' click='deptTreeListLoad()'>重新加载</a>]").show();
		}
	});
}



function onClick(event, treeId, treeNode, clickFlag) {
	selectedNodeTemp = treeNode;
	$("#baseDeptId").val(treeNode.id);
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	var nodes = treeObj.getNodesByParam("id", treeNode.pId, null);
	$("#deptName").val(treeNode.name);
	var parentDeptName = "暂无";
	var baseParentDeptId = "";
	if(nodes != null && nodes.length > 0){
		parentDeptName = nodes[0].name;
		baseParentDeptId = treeNode.pId;
	}
	$("#baseParentDeptId").val(baseParentDeptId);
	$("#parentDept").val(parentDeptName);
	$("#deptLeaderRealName").val(showMsgLeaderInfo(treeNode.realName));
	$("#deptLeaderTelPhone").val(showMsgLeaderInfo(treeNode.userTelPhone));
	$("#deptLeaderPhone").val(showMsgLeaderInfo(treeNode.userPhone));
}

function showMsgLeaderInfo(info){
	return (typeof(info) !== "undefined" && info !== null && info !== "") ? info : "暂无";
}

function saveDeptInfo(){
	try{
		const deptId = $("#deptId_insert").val();
		const deptName = $("#deptName_insert").val();
		const parentDept = $("#"+treeSelectInputId).attr("data-tree-id");
		const userLeader = $('#deptLeaderRealName_insert').select2('val');
		
		if(typeof(deptName) === 'undefined' || deptName === null || deptName === ""){
			toastr.warn("请填写部门名称！","提示信息");
			throw new Error("保存部门数据时，部门名称没有填写");
		}
		var requestJson = "{'deptName':'"+deptName+"'";
		if(typeof(deptId) !== 'undefined' && deptId != null && deptId !== ""){
			requestJson = requestJson + ",'deptId':"+deptId+"";
		}
		if(typeof(parentDept) !== 'undefined' && parentDept != null && parentDept !== ""){
			requestJson = requestJson + ",'parentDept':"+parentDept+"";
		}
		if(typeof(userLeader) !== 'undefined' && userLeader != null && userLeader !== ""){
			requestJson = requestJson + ",'leaderId':"+userLeader+"";
		}
	    requestJson = requestJson + "}";
		
		$.ajax({
			url:"/sysDept/save",
			type:"POST",
			contentType: "application/json;charset=UTF-8",
			timeout:10000,
			data:requestJson,
			async:true,
			cache:false,
			dataType:"json",
			success:function(data){
				if(data.code === 200){
					toastr.success("保存部门信息成功！","提示信息");
					$("#insertDeptInfoModal").modal('hide');
					var saveAfterDeptId = (typeof(deptId) === "undefined" || deptId == null || deptId.toString().trim() === "") ? "" : deptId;
					deptTreeListLoad(saveAfterDeptId);
				}else{
					toastr.error(data.msg,"提示信息");
				}
			},error:function(e){
				toastr.error("保存部门信息异常，请联系【系统管理员】！","提示信息");
			}
		});
	}catch(e){
		console.log(e);
	}
}

function resetSaveForm(){
	$("#deptId_insert").val("");
	$("#deptName_insert").val("");
	$("#"+treeSelectInputId).val("");
	$("#"+treeSelectInputId).attr("data-tree-id","");
	$('#deptLeaderRealName_insert').val(null).trigger('change');
}

function selectedNodeSyncForm(){
	if(selectedNodeTemp != null){
		if(typeof (selectedNodeTemp.id) !== "undefined" && selectedNodeTemp.id  != null && (selectedNodeTemp.id).toString().trim() !== ""){
			$("#deptId_insert").val(selectedNodeTemp.id);
		}else{
			$("#deptId_insert").val("");
		}
		if(typeof (selectedNodeTemp.name) !== "undefined" && selectedNodeTemp.name  != null && (selectedNodeTemp.name).toString().trim() !== ""){
			$("#deptName_insert").val(selectedNodeTemp.name);
		}else{
			$("#deptName_insert").val("");
		}
		
		if(typeof (selectedNodeTemp.pId) !== "undefined" && selectedNodeTemp.pId  != null && (selectedNodeTemp.pId).toString().trim() !== ""){
			var treeObj = $.fn.zTree.getZTreeObj("deptTreeData");
			var nodes = treeObj.getNodesByParam("id", selectedNodeTemp.pId, null);
			var parentDeptName = "暂无";
			if(nodes != null && nodes.length > 0){
				parentDeptName = nodes[0].name;
			}
			deptSelectCompoment(selectedNodeTemp.pId);
			$("#"+treeSelectInputId).val(parentDeptName);
			$("#"+treeSelectInputId).attr("data-tree-id",selectedNodeTemp.pId);
		}else{
			$("#"+treeSelectInputId).val("");
			$("#"+treeSelectInputId).attr("data-tree-id","");
		}
		
		
	}
}


function confirmDelInfo(){
	$("#deleteDeptInfoModal").modal('hide');
	$.ajax({
		url:"/sysDept/del",
		type:"POST",
		timeout:10000,
		data:{"_method":"DELETE","deptId":$("#baseDeptId").val()},
		async:true,
		cache:false,
		dataType:"json",
		success:function(data){
			if(data.code === 200){
				toastr.success("删除部门信息成功！","提示信息");
				var treeObj = $.fn.zTree.getZTreeObj("deptTreeData");
				var saveAfterDeptId =  "";
				var nodes = treeObj.getNodesByParam("id",$("#baseDeptId").val(), null);
				if(nodes != null && nodes.length > 0){
					saveAfterDeptId = nodes[0].pId;
				}
				deptTreeListLoad(saveAfterDeptId);
			}else{
				toastr.error(data.msg,"提示信息");
			}
		},error:function(){
			toastr.error("删除部门信息异常，请联系【系统管理员】！","提示信息");
		}
	});
}


function deptSelectCompoment(thisId){
	var treeObj = $.fn.zTree.getZTreeObj(treeSelectInputId+"_treeDom");
	var nodes = treeObj.getNodesByParam("id", thisId, null);
	if(typeof(nodes) !== "undefined" && nodes != null && nodes.length > 0){
		treeObj.selectNode(nodes[0]);
	}
}
